#include "common.h"

#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <sys/wait.h>

//获得命令本身
static const char *com_str(const char *command)
{

	char *temp = NULL;
	temp = (char *)malloc(strlen(command) + 1);
	assert(temp);

	int i = 0;
	while(*command != ' ')
	{
		temp[i] = *command;
		i++;
		command++;
	}

	return temp;
}

//获得命令参数
static const char *par_str(const char *command)
{
	char *temp = NULL;
	temp = (char *)malloc(strlen(command) + 1);
	assert(temp);

	int i = 0;
	while(*command != ' ')
		command++;

	command++;

	while(*command != '\0')
	{
		temp[i] = *command;
		i++;
		command++;
	}

	return temp;
}

int mysystem(const char *command)
{
	if(command == NULL)
	{
		err_sys("Input error!\n");
		return 127;
	}
	else
	{
		pid_t pid;
		pid_t child_pid;
		int status;

		char *const ps_argv[] = {com_str(command), par_str(command), NULL};

		pid = fork();
		if(pid < 0)
		{
			err_sys("fork error !\n");
			return -1;
		}
		else if(pid == 0)
		{
			printf("child process\n");
			printf("Child pid : %d\n", getpid());
			printf("Child ppid : %d\n", getppid());
			execvp(com_str(command), ps_argv);
		}
		else
		{
			printf("parent process\n");
			printf("parent pid : %d\n", getpid());

			child_pid = wait(&status);
			printf("Child process pid : %d\n", child_pid);
			if(WIFEXITED(status) != 0)
			{
				printf("child process exited with code %d\n", WEXITSTATUS(status));
				return (WEXITSTATUS(status));
			}
			else
			{
				printf("child process exited abnormally\n");
			}
		}
	}
}

int main(void)
{
	int ret = mysystem("ps -ax");
	printf("Return val : %d\n", ret);
	return 0;
}
